package com.opNaga.bpmp.connectingObject.messageFlow;

import com.opNaga.bpmp.BPMPElement;
import com.opNaga.bpmp.connectingObject.ConnectingObject;

/**
 * User: Junyi BEI
 * Date: 19/01/2012
 * Time: 14:01
 */
public class MessageFlow extends ConnectingObject {
  public MessageFlow() {
    super();
  }

  public MessageFlow(String t) {
    super(t);
  }

  @Override
  public String getType() {
    return "Message Flow";
  }

  @Override
  public boolean destroy() {
    if(source != null && !((MessageFlowSource) source).removeOutwardMessageFlow(this)) {
      return standardMessage(810, source);
    }
    if(target != null && !((MessageFlowTarget) target).removeInwardMessageFlow(this)) {
      return standardMessage(811, source);
    }
    return super.destroy();
  }

  @Override
  public boolean validateTarget(BPMPElement targetElement) {
    if(!MessageFlowTarget.class.isAssignableFrom(targetElement.getClass())) {
      return standardMessage(350, targetElement);
    }
    BPMPElement root = ((MessageFlowTarget) targetElement).getRoot();
    if(root == null) {
      return standardMessage(351, targetElement);
    }
    if(source != null && ((MessageFlowTarget) targetElement).getRoot() == ((MessageFlowSource) source).getRoot()) {
      return standardMessage(353, targetElement, source);
    }
    if(!((MessageFlowTarget) targetElement).addInwardMessageFlow(this)) {
      return standardMessage(354, targetElement);
    }
    return standardMessage(392, targetElement);
  }

  @Override
  public boolean validateSource(BPMPElement sourceElement) {
    if(!MessageFlowSource.class.isAssignableFrom(sourceElement.getClass())) {
      return standardMessage(360, sourceElement);
    }
    BPMPElement root = ((MessageFlowSource) sourceElement).getRoot();
    if(root == null) {
      return standardMessage(361, sourceElement);
    }
    if(target != null && root == ((MessageFlowTarget) target).getRoot()) {
      return standardMessage(363, sourceElement, target);
    }
    if(!((MessageFlowSource) sourceElement).addOutwardMessageFlow(this)) {
      return standardMessage(364, sourceElement);
    }
    return standardMessage(393, sourceElement);
  }
}
